<template>
<div class="container">
    <div class="card">
        <el-breadcrumb separator="/" class="card-body">
            <el-breadcrumb-item :to="{ path: '/AdminHome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/UserManagement' }">系统用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{ this.$route.meta.title }}</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="card">
        <div class="card-header">填写用户信息</div>
        <div class="card-body">
            <div class="login-log">
                <h4>登录信息</h4>
                <hr>
                <p>账户创建时间：{{ createdAccountTime }}</p>
                <p>上次登录时间：{{ lastLoginTime }}</p>
                <p>上次登录IP：{{ lastLoginIPadress }}</p>
            </div>
            <div class="avatar-uploader d-flex el-form-item el-form-item--small" v-loading.fullscreen.lock="isLoading">
                <label for="name" class="el-form-item__label" style="width: 100px;">照片</label>
                <div class="el-upload el-upload--text">
                    <img :src="userForm.headPhotoUrl" width="100%" height="100%" class="avatar">
                </div>
            </div>
            <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px">
                <div class="info-userInfo">
                    <el-form-item label="姓名">
                        <el-input :value="userForm.name" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-input :value="userForm.sex | sex" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="身份证号码" prop="identityNo">
                        <el-input :value="userForm.identityNo" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="工位号">
                        <el-input :value="userForm.jobNo" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="房间号" prop="roomId">
                        <el-input v-model="userForm.roomId" type="number" placeholder="请输入房间号,例如 3-1001"></el-input>
                    </el-form-item>
                    <el-form-item label="工位电话" prop="jobMobile">
                        <el-input v-model="userForm.jobMobile"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="所属部门">
                        <el-input v-model="department" maxlength="0" placeholder="点击 '查找' 选择部门" ref="userFind"></el-input>
                        <el-button type="text" size="medium" class="el-query-tree" @click="$tree('查找组织','userFind')">查找</el-button>
                    </el-form-item>
                    <el-form-item label="职位" prop="position">
                        <el-input v-model="userForm.position"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" v-model="userForm.remark"></el-input>
                    </el-form-item>
                </div>
                <hr>
                <div class="info-ruleForm">
                    <el-form-item label="登录账号" prop="account">
                        <el-input v-model.trim="userForm.account" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="设置密码" prop="newPassword">
                        <el-input v-model.trim="userForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="rePassword">
                        <el-input v-model.trim="userForm.rePassword" type="password" placeholder="再次请输入新密码"></el-input>
                    </el-form-item>
                    <el-form-item label="账号启用" prop="status">
                        <el-switch v-model="statusCode" @change="switchStatus(statusCode)"></el-switch>
                    </el-form-item>
                </div>
                <div class="authorization-list">
                    <el-form-item label="权限分配">
                        <el-tree ref="tree" :data="AuthorizationList" show-checkbox node-key="id" :props="defaultProps" :default-checked-keys="checkedKeys" :default-expanded-keys="expandedKeys" @check-change="handleCheckChange" class="authList">
                        </el-tree>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('userForm')">保存修改信息</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</div>
</template>

<script>
import { SET_TIME_YYMMDDHHMM } from "@/utils/formatTime.js";
import request from "@/utils/request";
export default {
  name: "UserDetail",
  data() {
    return {
      statusCode: true,
      defaltAvatar: "static/images/defalt_avatar.png",
      createdAccountTime: "-",
      lastLoginIPadress: "-",
      lastLoginTime: "-",
      isLoading: false,
      userForm: {
        headPhotoUrl: "",
        name: "",
        sex: "",
        secretLevel: "",
        identityNo: "",
        jobNo: "",
        jobMobile: "",
        email: "",
        department: {
          id: "",
          label: ""
        },
        position: "",
        remark: "",
        roomId: "",
        account: "",
        newPassword: "",
        rePassword: "",
        status: "",

        permissonIdList: []
      },
      rules: {
        jobMobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            min: 8,
            max: 11,
            message: "长度在 8 到 11 位工位号码",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 8, max: 64, message: "请输入正确邮箱格式", trigger: "blur" }
        ],
        department: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "请输入房间号", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ],
        position: [
          { required: true, message: "请输入职位", trigger: "blur" },
          { min: 2, max: 18, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        newPassword: [
          { min: 2, max: 18, message: "长度在 2 到 18 个字符", trigger: "blur" }
        ],
        rePassword: [
          { min: 2, max: 18, message: "长度在 2 到 18 个字符", trigger: "blur" }
        ]
      },
      defaultProps: {
        children: "children",
        label: "meunName"
      },
      //权限默认数据
      AuthorizationList: [],
      checkedKeys: [],
      expandedKeys: ["1", "2"]
    };
  },
  filters: {
    sex(sex) {
      if (sex == "0") {
        return "男";
      } else if (sex == "1") {
        return "女";
      } else {
        return "未知性别";
      }
    }
  },
  methods: {
    switchStatus(br) {
      console.log(br);
      if (br) {
        this.userForm.status = "1";
      } else {
        this.userForm.status = "0";
      }
    },
    getUserInfo() {
      //获取用户信息渲染到页面
      let userId = this.$route.query.userid;
      this.isLoading = true;
      request({
        url: this.$api.getUserDetail + "?id=" + userId, //链接参数增加:  "userid?=" + userId
        method: "get"
      })
        .then(res => {
          // 用户数据注入到表单数据
          this.userForm = res.data;
          //把权限列表注入显示到树上
          let checkedKeysList = [];
          for (let list of res.data.permissonIdList) {
            checkedKeysList.push(list.id);
          }
          this.checkedKeys = checkedKeysList;

          if (!res.data.department) {
            this.userForm.department = {
              id: "",
              label: "暂未设置部门"
            };
          }

          // this.createdAccountTime = SET_TIME_YYMMDDHHMM(res.data.joinTime);
          // this.lastLoginTime = SET_TIME_YYMMDDHHMM(res.data.lastLoginTime);
          // this.lastLoginIPadress = res.data.lastLoginIPadress;
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    getAllPermisson() {
      request({
        url: this.$api.getAllPermisson,
        method: "get"
      }).then(res => {
        this.AuthorizationList = res.data;
      });
    },
    handleCheckChange(data, checked, indeterminate) {
      // console.log(data, checked);
      let id = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      let checkData = [];
      for (let val of id) {
        checkData.push({
          id: val
        });
      }
      this.userForm.permissonIdList = checkData;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let userData = this.userForm;
          request({
            url: this.$api.updateUser,
            method: "post",
            data: userData
          }).then(res => {
            if (res.code === "000000") {
              this.$message.success("更新新用户成功");
              setTimeout(() => {}, 500);
            }
          });
        } else {
          return false;
        }
      });
    }
  },
  mounted() {
    this.getUserInfo();
    this.getAllPermisson();
  },
  computed: {
    //注册树形菜单数据
    department: function() {
      if (this.$store.getters.treeData.ref !== "userFind") {
        return this.userForm.department.label;
      } else {
        this.userForm.department.label = this.$store.getters.treeData.val;
        this.userForm.department.id = this.$store.getters.treeData.id;
        return this.$store.getters.treeData.val;
      }
    }
  }
};
</script>
<style scoped>
.info-userInfo {
  width: 420px;
  position: relative;
}
.authList {
  border: 1px solid #f2f2f2;
  padding: 0.5rem 1rem;
  width: 420px;
}
</style>